//
//  19.顺时针打印矩阵.swift
//  数据结构与算法
//
//  Created by ZERO on 2021/5/19.
//

import Foundation
/*
 题目：输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，例如，如果输入如下4 X 4矩阵： 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
 思路：四个方向，j+, i+, j-, i-
    
 */
func offer_19() {
    print(Solution().printMatrix(
            [
                [ 1,  2,  3,  4],
                [ 5,  6,  7,  8],
                [ 9, 10, 11, 12],
                [13, 14, 15, 16]
            ]
    ))
}

fileprivate class Solution {
    func printMatrix(_ matrix: [[Int]]) -> [Int] {
        // write code here
        guard matrix.first?.first != nil else { return [] }
        let row = matrix.count
        let col = matrix.first!.count
        var printArr = [Int]()
        // 四个方向，j+, i+, j-, i-
        var direction = 0
        var left = 0, right = col - 1, top = 0, bottom = row - 1
        while left <= right && top <= bottom {
            switch direction {
            case 0:
                for i in left...right {
                    printArr.append(matrix[top][i])
                }
                top += 1
            case 1:
                for i in top...bottom {
                    printArr.append(matrix[i][right])
                }
                right -= 1
            case 2:
                for i in (left...right).reversed() {
                    printArr.append(matrix[bottom][i])
                }
                bottom -= 1
            case 3:
                for i in (top...bottom).reversed() {
                    printArr.append(matrix[i][left])
                }
                left += 1
            default:
                break
            }
            direction += 1
            direction %= 4
        }
        return printArr
    }
}

